package com.c.ctgproject.ui.sell.parts

import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import com.c.ctgproject.R
import com.c.ctgproject.adapter.PartSellListAdapter
import com.c.ctgproject.base.BaseActivity
import com.c.ctgproject.entity.PartsSellListEntity
import com.c.ctgproject.utils.CustomToast
import com.c.ctgproject.utils.MyLog
import com.c.ctgproject.utils.getGson
import com.c.ctgproject.utils.initData
import kotlinx.android.synthetic.main.activity_parts_sell.*
import java.util.ArrayList

/**
 *作者:LiBW
 *创建日期: 2020/9/8
 *描述:配件销售列表页面
 */
class PartsSellListActivity : BaseActivity() {
    private val mListViewModel: PartsSellListViewModel by lazy { ViewModelProvider(this)[PartsSellListViewModel::class.java] }
    private val mList = ArrayList<PartsSellListEntity.DataBean.ListBean>()
    private val mAdapter: PartSellListAdapter by lazy { PartSellListAdapter(this, mList) }
    private var page = 1
    private val size = 5

    override fun getLayout() = R.layout.activity_parts_sell

    override fun event() {
        changeTransparentStatusBar()
        changeStatusIconColor(true)
        mPartsDetailListRV.adapter = mAdapter
        mPartsDetailListRV.layoutManager = LinearLayoutManager(this)
        //获取详情
        mListViewModel.getDetail(page, size)
        //详情回调
        mListViewModel.detail.observe(this, Observer {
            mRefresh.finishRefresh()
            mRefresh.finishLoadMore()
            MyLog.d("配件详情回调:$it")
            val data = initData(it)
            if (data.status == 0) {
                mRefresh.finishLoadMore()
                mRefresh.finishRefresh()
                val entity = getGson().fromJson(it, PartsSellListEntity::class.java).data
                if (entity==null) MyLog.d("entity是空的")
                if (entity?.list==null) MyLog.d("entity是空的")
                entity?.list?.let { list ->
                    mList.addAll(list)
                    mAdapter.notifyDataSetChanged()
                }
            } else {
                CustomToast.showToast(this, data.msg.toString())
            }
        })
        //通用错误回调
        mListViewModel.error.observe(this, Observer {
            CustomToast.showToast(this, it)
        })
    }

    override fun click() {
        //下拉刷新
        mRefresh.setOnRefreshListener {
            //获取详情
            mList.clear()
            page = 1
            mListViewModel.getDetail(page, size)
        }
        //上啦加载
        mRefresh.setOnLoadMoreListener {
            //获取详情
            page++
            mListViewModel.getDetail(page, size)
        }
    }

}